package club.banyuan.reserve.controller.api;

import club.banyuan.reserve.common.ApiResponse;
import club.banyuan.reserve.common.CommonResult;
import club.banyuan.reserve.config.JwtUtils;
import club.banyuan.reserve.dao.AuthDao;
import club.banyuan.reserve.dto.UserParam;
import club.banyuan.reserve.model.Role;
import club.banyuan.reserve.model.User;
import club.banyuan.reserve.service.UserService;
import cn.hutool.crypto.digest.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author HanChao
 * 描述信息：用户登录、登出、注册
 */
@RestController
@RequestMapping(value = "/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping(value = "/login")
    public CommonResult login (@RequestBody UserParam param,
                               HttpSession session) {

        User user = userService.userLogin(param.getUsername(), param.getPassword());

        if (user == null) {
            return CommonResult.failed("用户名，密码错误");
        }

        // 校验密码
        try {
            if (!BCrypt.checkpw(param.getPassword(), user.getPassword())) {

                return CommonResult.failed("用户名，密码错误");
            }
        } catch (Exception e) {

            e.printStackTrace();
            return CommonResult.failed("用户名，密码错误");
        }

//        // 鉴权
//        List<Role> roleByUserId = authDao.findRoleByUserId(user.getId());

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(param.getUsername(), param.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);

        String token = jwtUtils.createJWT(authentication, true);
        Map<String, String> info = new HashMap<>();
        info.put("token", token);
        return CommonResult.success(info);
    }

    @PostMapping(value = "/logout")
    public CommonResult logout (HttpServletRequest request) {

        try {
            // 设置JWT过期
            jwtUtils.invalidateJWT(request);
        } catch (SecurityException e) {
            return CommonResult.forbidden("请先登录");
        }
        return CommonResult.success("退出成功");
    }

    @PostMapping(value = "/register")
    public CommonResult register (@RequestBody UserParam param) {

        boolean b = userService.userRegister(param.getUsername(), param.getPassword());

        if (b == false) {

            return CommonResult.failed("用户名已存在");
        }

        return CommonResult.success("OK");
    }

    @GetMapping(value = "/current")
    public CommonResult current (HttpServletRequest request) {

        // 从Redis中取出当前用户名
        String jwt = jwtUtils.getJwtFromRequest(request);
        String username = jwtUtils.getUsernameFromJWT(jwt);

        return CommonResult.success(username);
    }
}
